package com.hanson.common.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class HttpClientUtil {
    public static String sendGet(String url) {
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        try {
            getMethod.addRequestHeader("accept-encoding", "gzip,deflate");
            getMethod.addRequestHeader("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Alexa Toolbar; Maxthon 2.0)");

            int result = httpClient.executeMethod(getMethod);
            if (result == 200) {
                String html = getMethod.getResponseBodyAsString();
                return html;
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            getMethod.releaseConnection();
        }
        return null;
    }

    public static String sendPost(String url, String requestContent) {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        try {
            postMethod.addRequestHeader("accept-encoding", "gzip,deflate");
            postMethod.addRequestHeader("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Alexa Toolbar; Maxthon 2.0)");
            RequestEntity requestEntity = new StringRequestEntity(
                    requestContent, /*"text/html"*/"application/json", "utf-8");
            postMethod.setRequestEntity(requestEntity);
            postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
            int httpResult = httpClient.executeMethod(postMethod);
            if (httpResult == HttpStatus.SC_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        postMethod.getResponseBodyAsStream()));
                StringBuffer stringBuffer = new StringBuffer();
                String buffer = "";
                while (null != (buffer = (in.readLine()))) {
                    stringBuffer.append(buffer).append("\r\n");
                }
                String result = stringBuffer.toString();
                return result;
            } else {
                System.out.println("请求未正常处理");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        return null;
    }
}
